# 模拟 ansible 的项目

## 思路

### 解析本地配置

### 连接远端机器

### 控制任务执行

#### ssh连接并执行命令；在控制端主机属于执行网络io密集任务，适合使用 concurrent.futures 多线程

from concurrent.futures  import ThreadPoolExecutor

from project.ssh01 import execute_remote_command
from config import load_configuration
def execute_tasks(hosts, tasks):
    with ThreadPoolExecutor() as executor: # 创建任务并发执行的线程池
        
        futures = [] # 用以存放并保留所有的目标和任务
        for  host in hosts: # 每个主机都需要同样执行
            for task in tasks: # 每个任务都需要执行
                future = executor.submit( # 提交一个任务到线程池中执行, 且会返回future
                    # 调用函数，取字典中的值传入参数
                    execute_remote_command, host['address'], host['port'], task['command'], 
                    host['username'], host['password']
                )
                futures.append(future)

        for future in futures:
            output, error = future.result()
            if error:
                print(f'Error: {error}')
            else:
                print(f'Output: {output}')


if __name__ == '__main__':
    conf = load_configuration('playbook.yaml')
    execute_tasks(conf['host'], conf['tasks'])

    